import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { successResponse, errorResponse } from '@/lib/response';

// POST /api/admin/friendly-links/update - 更新友情链接
async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const { id, ...data } = await req.json();

  if (!id) {
    return errorResponse('缺少ID');
  }

  const payload: any = {};
  if (data.name !== undefined) payload.name = data.name;
  if (data.url !== undefined) payload.url = data.url;
  if (data.order !== undefined) payload.order = Number(data.order) || 0;
  if (data.isActive !== undefined) payload.isActive = Number(data.isActive);

  const updated = await prisma.friendlyLink.update({
    where: { id },
    data: payload,
  });

  return successResponse(updated, '更新成功');
}

export const POST = withMiddleware(handler);